package com.yanjiang;

import java.sql.*;

public  class BaseDao {
    static Connection connection=null;
    static PreparedStatement preparedStatement=null;
    static Statement statement=null;
    static ResultSet resultSet=null;



    //建立数据库连接
    public static Connection getConnection(){
        Connection connection =null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url="jdbc:mysql://127.0.0.1:3306/kgcnews";
            String username="root";
            String pass="123456";
            connection=DriverManager.getConnection(url,username,pass);
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }






    //查
    public static ResultSet selectObj(String sql ,Object[] obj)  {
        connection=BaseDao.getConnection();
        try {
            preparedStatement=connection.prepareStatement(sql);
            if (obj!=null){
                for (int i=0;i<obj.length;i++){
                    preparedStatement.setObject(i+1,obj[1]);
                }
                resultSet=preparedStatement.executeQuery();
            }else {
                resultSet=preparedStatement.executeQuery();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Connection connection=null;
            PreparedStatement preparedStatement=null;
            Statement statement=null;
            ResultSet resultSet=null;
            closeConnect(connection,preparedStatement,statement,resultSet);
        }
        return resultSet;
    }

    //增 删 改
    public static int  updateObj(String sql,Object[] obj){
        int rows=0;
        try {
            connection =  BaseDao.getConnection();
            preparedStatement=connection.prepareStatement(sql);
            if(obj !=null){
                for (int i=0;i<obj.length;i++){
                    preparedStatement.setObject(i+1, obj[i]);
                }
                rows= preparedStatement.executeUpdate();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Connection connection=null;
            PreparedStatement preparedStatement=null;
            Statement statement=null;
            ResultSet resultSet=null;
            BaseDao.closeConnect(connection,preparedStatement,statement,resultSet);
        }
        return rows;
    }
    //关闭连接
    public static  void closeConnect( Connection connection,PreparedStatement preparedStatement,Statement statement,ResultSet resultSet){
        try{
            if (resultSet !=null){
                resultSet.close();
            }
            if (preparedStatement !=null){
                preparedStatement.close();
            }
            if (statement !=null){
                statement.close();
            }
            if (connection !=null){
                connection.close();
            }

        }catch (Exception e){

        }
    }




}
